<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="商品编号" prop="cid">
        <el-input
          v-model="queryParams.cid"
          placeholder="请输入商品编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="gname">
        <el-input
          v-model="queryParams.gname"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品图片" prop="gimg">
        <el-input
          v-model="queryParams.gimg"
          placeholder="请输入商品图片"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="sn号" prop="gsn">
        <el-input
          v-model="queryParams.gsn"
          placeholder="请输入sn号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="原价" prop="price">
        <el-input
          v-model="queryParams.price"
          placeholder="请输入原价"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="售价" prop="saleprice">
        <el-input
          v-model="queryParams.saleprice"
          placeholder="请输入售价"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="详情题目" prop="detailtitle">
        <el-input
          v-model="queryParams.detailtitle"
          placeholder="请输入详情题目"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="库存" prop="stock">
        <el-input
          v-model="queryParams.stock"
          placeholder="请输入库存"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预警库存" prop="lowstock">
        <el-input
          v-model="queryParams.lowstock"
          placeholder="请输入预警库存"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单位" prop="unit">
        <el-input
          v-model="queryParams.unit"
          placeholder="请输入单位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="重量" prop="weight">
        <el-input
          v-model="queryParams.weight"
          placeholder="请输入重量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="售完时间" prop="publishstate">
        <el-date-picker
          clearable
          v-model="queryParams.publishstate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择售完时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="赠送的积分" prop="giftpoint">
        <el-input
          v-model="queryParams.giftpoint"
          placeholder="请输入赠送的积分"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="验证状态" prop="verifystate">
        <el-input
          v-model="queryParams.verifystate"
          placeholder="请输入验证状态"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <el-button
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></el-button>
    </el-row>

    <el-table
      v-loading="loading"
      :data="goodsList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="类别编号" align="center" prop="gid" />
      <el-table-column label="商品编号" align="center" prop="cid" />
      <el-table-column label="商品名称" align="center" prop="gname" />
      <el-table-column label="商品图片" align="center" prop="gimg">
        <template slot-scope="scope" >
          <!-- v-if="scope.row.gimg" -->
          <img
            :src="$baseUrl + '/' + imgs"
            :width="50"
            :height="50"
            v-for="imgs in scope.row.gimg.split(',')" :key="imgs"
          />
        </template>
         <!-- <template slot-scope="scope" v-else>
          <span>无图片</span>
        </template> -->
      </el-table-column>

      <el-table-column label="sn号" align="center" prop="gsn" />
      <el-table-column label="原价" align="center" prop="price" />
      <el-table-column label="售价" align="center" prop="saleprice" />
      <el-table-column label="描述" align="center" prop="description" />
      <el-table-column label="详情题目" align="center" prop="detailtitle" />
      <el-table-column label="库存" align="center" prop="stock" />
      <el-table-column label="预警库存" align="center" prop="lowstock" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="重量" align="center" prop="weight" />
      <el-table-column
        label="到货时间"
        align="center"
        prop="publishstate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.publishstate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="赠送的积分" align="center" prop="giftpoint" />
      <el-table-column label="验证状态" align="center" prop="verifystate" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      small
      v-show="total > 0"
      :total="total"
      :current-page.sync="queryParams.pageNum"
      :page-size.sync="queryParams.pageSize"
      background
      layout="prev,pager,next"
      @current-change="getList"
    />

    <!-- 添加或修改goods对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品编号" prop="cid">
          <el-input v-model="form.cid" placeholder="请输入商品编号" />
        </el-form-item>
        <el-form-item label="商品名称" prop="gname">
          <el-input v-model="form.gname" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品图片" prop="gimg">
          <el-input type="hidden" v-model="form.gimg" />
          <!-- 图片上传 -->
          <el-upload
            :action="$baseUrl + '/upload'"
            ref="upload"
            class="upload-demo"
            :on-remove="handleRemove"
            :file-list="fileList"
            :on-success="handleAvatarSuccess"
            :auto-upload="false"
          >
            <el-button slot="trigger" size="small" type="primary"
              >选取文件</el-button
            >
            <el-button
              style="margin-left: 10px"
              size="small"
              type="success"
              @click="submitUpload"
              >上传到服务器</el-button
            >
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
          |
        </el-form-item>
        <!-- <el-upload
            class="avatar-uploader"
            :action="$baseUrl + '/upload'"
            :headers="{ Authorization: 'Bearer ' + $store.getters.token }"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="form.gimg"
              :src="$baseUrl + '/' + form.gimg"
              class="avatar"
              height="80"
              width="80"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon" height="80" width="80"></i>
          </el-upload> -->
        <el-form-item label="sn号" prop="gsn">
          <el-input v-model="form.gsn" placeholder="请输入sn号" />
        </el-form-item>
        <el-form-item label="原价" prop="price">
          <el-input v-model="form.price" placeholder="请输入原价" />
        </el-form-item>
        <el-form-item label="售价" prop="saleprice">
          <el-input v-model="form.saleprice" placeholder="请输入售价" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="详情题目" prop="detailtitle">
          <el-input v-model="form.detailtitle" placeholder="请输入详情题目" />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input v-model="form.stock" placeholder="请输入库存" />
        </el-form-item>
        <el-form-item label="预警库存" prop="lowstock">
          <el-input v-model="form.lowstock" placeholder="请输入预警库存" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="重量" prop="weight">
          <el-input v-model="form.weight" placeholder="请输入重量" />
        </el-form-item>
        <el-form-item label="到货时间" prop="sendtime">
          <el-date-picker
            clearable
            v-model="form.sendtime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择到货时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="赠送的积分" prop="giftpoint">
          <el-input v-model="form.giftpoint" placeholder="请输入赠送的积分" />
        </el-form-item>
        <el-form-item label="验证状态" prop="verifystate">
          <el-input v-model="form.verifystate" placeholder="请输入验证状态" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listGoods,
  getGoods,
  delGoods,
  addGoods,
  updateGoods,
} from "@/api/system/goods";

export default {
  name: "Goods",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // goods表格数据
      goodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        cid: null,
        gname: null,
        gimg: null,
        gsn: null,
        price: null,
        saleprice: null,
        description: null,
        detailtitle: null,
        stock: null,
        lowstock: null,
        unit: null,
        weight: null,
        publishstate: null,
        giftpoint: null,
        verifystate: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      fileList: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
     submitUpload() {
    this.$refs.upload.submit(); // 调用 el-upload 的 submit 方法
  },
    parseTime(time) {
      // 你的时间格式化逻辑，例如：
      return new Date(time).toLocaleString();
    },
    /** 查询goods列表 */
    getList() {
      this.loading = true;
      listGoods(this.queryParams).then((response) => {
        this.goodsList = response.data.rows;
        this.total = response.data.totalsize;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        gid: null,
        cid: null,
        gname: null,
        gimg: null,
        gsn: null,
        price: null,
        saleprice: null,
        description: null,
        detailtitle: null,
        stock: null,
        lowstock: null,
        unit: null,
        weight: null,
        publishstate: null,
        giftpoint: null,
        verifystate: null,
      };
      this.$nextTick(() => {
        this.$refs["form"].resetFields();
      });
      // this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    // 头像上传
    handleAvatarSuccess(res, file) {
      //上传成功之后的回调函数
      // this.imageUrl = URL.createObjectURL(file.raw);
      // this.form.gimg = res.data;
      // console.log(this.form.gimg);
      console.log(res.data + " ");
      this.fileList.push(res.data);
      console.log(this.fileList);
    },

    handleRemove(file, fileList) {
      this.fileList = [];
      fileList.forEach((item) => {
        this.fileList.push(item.name);
      });
    },

    beforeAvatarUpload(file) {
      //限制文件类型及大小
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.$nextTick(() => {
        this.$refs["queryForm"].resetFields();
      });
      // this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.gid);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加goods";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const gid = row.gid || this.ids;
      getGoods(gid).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改goods";
        this.fileList = [];
        if (this.form.gimg != null) {
          const names = this.form.gimg.split(",");
          names.forEach((item) => {
            this.fileList.push({ name: item });
          });
        }
        console.log(this.fileList);
      });
    },
    /** 提交按钮 */
    // submitForm() {
    //   this.$refs["form"].validate(valid => {
    //     if (valid) {
    //       if (this.form.gid != null) {
    //         updateGoods(this.form).then(response => {
    //           this.$modal.msgSuccess("修改成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       } else {
    //         addGoods(this.form).then(response => {
    //           this.$modal.msgSuccess("新增成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       }
    //     }
    //   });
    // },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.gid != null) {
            console.log(this.fileList.length + " ");
            if (this.fileList.length > 0) {
              this.form.gimg = this.fileList.join(",");
              // this.form.gimg = this.fileList.map(item=>item.name).join(",");
            }
            console.log(this.form.gimg + " ");
            updateGoods(this.form).then((response) => {
              this.$message({ type: "success", message: "修改成功" });
              // this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            console.log(this.fileList.length+" ");
            if(this.fileList.length>0){
              // this.form.gimg = this.fileList.map(item=>item.name).join(",");
             this.form.gimg = this.fileList.join(",");
            }
            console.log(this.form.gimg+" ");
            addGoods(this.form).then((response) => {
              this.$message({ type: "success", message: "新增成功" });
              // this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    // handleDelete(row) {
    //   const gids = row.gid || this.ids;
    //   this.$modal.confirm('是否确认删除goods编号为"' + gids + '"的数据项？').then(function() {
    //     return delGoods(gids);
    //   }).then(() => {
    //     this.getList();
    //     this.$modal.msgSuccess("删除成功");
    //   }).catch(() => {});
    // },
    handleDelete(row) {
      const gids = row.gid || this.ids;
      this.$confirm(
        '是否确认删除category编号为"' + gids + '"的数据项？',
        "提示",
        { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" }
      )
        .then(function () {
          return delGoods(gids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/goods/export",
        {
          ...this.queryParams,
        },
        `goods_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
